package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils2;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录时获取验证码
     * @param user
     * @param
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user){
        String phone = user.getPhone();
        //如果手机号码不为空
        if (StringUtils.isNotBlank(phone)){
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //发送短信 用脸容云
           // SMSUtils2.sendMessage(phone,code);
            log.info("验证码: {}",code);
            //将验证码存储到session

//           session.setAttribute(phone,code);
                                       // user:code:13367301234
redisTemplate.opsForValue().set("user:code:" + phone, code,5, TimeUnit.MINUTES);
            return R.success();
        }

    return  R.error("手机号有误");
    }


    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map map, HttpSession session){
        //获取参数中的手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //校验验证是否正确
//       Object codeInSession = session.getAttribute(phone);
                                                // user:code:13367301234
       Object codeInRedis = redisTemplate.opsForValue().get("user:code:"+ phone);
        if (codeInRedis !=null&&codeInRedis.equals(code)){
            //登录成功，考虑是否需要注册
            User user=userService.registerIfUserNotExists(phone);
            //保存用户的登录状态
            session.setAttribute("user",user.getId());
        
            return R.success();
        }
        return R.error("登录失败");
    }

}
